package sanshui.system.trade.factory.data;

import lombok.Data;
import sanshui.system.trade.util.CommonTimeUtil;

import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.util.Map;
import java.util.NavigableMap;
import java.util.TreeMap;
import java.util.concurrent.ConcurrentSkipListMap;

@Data
public class KLineData {
    private NavigableMap<LocalDateTime, Bar> bars = new TreeMap<>(); // 按时间排序的K线
    private String frequency; // 1m,5m,1d
    private ConcurrentSkipListMap<Long, LocalDateTime> timeIndex = new ConcurrentSkipListMap<>();

    public void addBar(String frequency, Bar bar){
        setFrequency(frequency);
        LocalDateTime timestamp = bar.getTimestamp();
        bars.put(timestamp, bar);
        timeIndex.put(CommonTimeUtil.getTimestampToLong(timestamp), timestamp);
    }

    public Bar getNearestBar(LocalDateTime timestamp) {
        // 使用跳跃表实现O(logN)查询
        Long key = timestamp.toEpochSecond(ZoneOffset.UTC);
        Map.Entry<Long, LocalDateTime> entry = timeIndex.floorEntry(key);
        return entry != null ? bars.get(entry.getValue()) : null;
    }

    public Bar getNearestBar(Long timestamp) {
        // 使用跳跃表实现O(logN)查询
        Map.Entry<Long, LocalDateTime> entry = timeIndex.floorEntry(timestamp);
        return entry != null ? bars.get(entry.getValue()) : null;
    }
}
